<template>
  <div class="accessList">
    <div class="top">
      <div class="icon fl">
        <i class="V7_iconfont V7_iconV7tubiao_weixinxiaochengxu1"></i>
      </div>
      <div class="fl">
        <h5 class="title">对于访客端有更高要求的客户，系统提供基于微信小程序开发的sdk插件，客户可自定义配置访客端界面，
          配置后将插件集成到自己的<br/>微信小程序中即可完成对接</h5>
        <p class="version">小程序 SDK V1.0.0版本<a href="https://developer.7moor.com/v7/im-smallProgram/" target="blank">开发文档</a></p>
      </div>
      <el-button type="primary fr add" size="mini" @click="addFun" v-functions="['wechatApp_sdk_access_list_insert']">立即绑定</el-button>
    </div>
    <institutionTable ref="tableRef" class="instiutionTableBox"
      :pages="tablePages"
      :instiutionTableData="tableData"
      :instiutionTableHeader="tableHeader"
      @sizeChange="sizeChange"
      @currentChange="currentChangeFun">
    </institutionTable>
    <drawer
      direction="rtl"
      :title="drawer.title"
      :drawer="drawer.isShow"
      @save="confirmFun"
      @cancelFun="cancelFun"
      @closeDraw="cancelFun">
      <template slot="column">
        <sdkAccessAddOrEdit ref="sdkAccessInfo"></sdkAccessAddOrEdit>
      </template>
    </drawer>
  </div>
</template>
<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import institutionTable from '@/common/views/institutionTable/institutionTable.vue'
import sdkAccessAddOrEdit from '@/views/config/webchat/channel/wechatApp/sdkAccessAddOrEdit.vue'
import drawer from '@/common/views/drawer/index.vue'
import { CommonModule } from '@/store/modules/common'
import { channelConfigMoudle } from '@/store/modules/config/channel/index'
import { deepClone, randomWord } from '@/utils/common'
import funTab from '@/components/cardLayout/FunTab.vue'
import { ElForm } from 'element-ui/types/form'
import { checkPermission } from '@/utils/directive'
interface TablePagesObj {
  current: number
  pageSize: number
  total: number
}
interface DrawerObj {
  isShow: boolean
  title: string
}
@Component({
  name: 'wechatAppSdkAccessList',
  components: { institutionTable, drawer, sdkAccessAddOrEdit, funTab }
})
export default class WechatAppSdkAccessList extends Vue {
  @Ref() private readonly sdkAccessInfo !: sdkAccessAddOrEdit
  private $message: any
  private $confirm: any
  private $store: any
  private $getCache: any

  private tabs: any = [
    { label: '基本信息', name: 'basic' },
    { label: '其他信息', name: 'otherInfo' }
  ]

  private limitArr: any = [] // 权限

  private satisfactionId: string = ''

  private tableHeader: any = [ // 列表表头
    { label: '小程序名称', prop: 'name' },
    { label: '流程', prop: 'processName' },
    { label: '创建人', prop: 'createName' },
    { label: '绑定时间', prop: 'createTime', isSort: true },
    { label: '最后更新时间', prop: 'updateTime', isSort: true, width: 145 }
  ]

  private drawer: DrawerObj = {
    isShow: false,
    title: '新增小程序'
  }

  private tablePages: TablePagesObj = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private tableData: any = [] // 列表数据

  private cancelFun () { // 取消
    this.drawer.isShow = false
    this.sdkAccessInfo.setAccessData()
  }

  private sizeChange (size: number) {
    this.tablePages.pageSize = size
    this.getTableList()
  }

  private currentChangeFun (page: number) {
    this.tablePages.current = page
    this.getTableList()
  }

  private editFun (row: any) { // 编辑
    this.drawer.isShow = true
    this.drawer.title = '编辑小程序'
    this.$nextTick(() => {
      row.satisfactionId = this.satisfactionId
      this.sdkAccessInfo.setAccessData(row)
    })
  }

  private addFun () { // 立即绑定
    this.drawer.isShow = true
    this.drawer.title = '新增小程序'
    this.$nextTick(() => {
      this.sdkAccessInfo.setAccessData()
    })
  }

  private delFun (row: any) { // 删除
    const sendData = { url: '/im-wxsdk/action/config/wxsdkChannel/delete', method: 'POST', data: { _id: row._id } }
    this.$confirm('确定要删除该小程序吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      channelConfigMoudle.channelCommonAction(sendData).then((res: any) => {
        if (res && res.success) {
          (this as any).$deleteCache('channelList', '_id', row._id, true)
          this.$message.success('删除小程序成功')
          this.getTableList()
        }
      })
    })
  }

  private confirmFun () { // 保存
    const formRef = this.sdkAccessInfo.$refs.accessForm as ElForm
    formRef.validate(valide => {
      if (valide) {
        const sendData = deepClone(this.sdkAccessInfo.accessForm)
        let sendUrl = '/im-wxsdk/action/config/wxsdkChannel/save'
        let successMsg = '添加小程序成功'
        if (sendData._id) {
          sendUrl = '/im-wxsdk/action/config/wxsdkChannel/update'
          successMsg = '编辑小程序成功'
        } else {
          sendData.satisfactionId = this.satisfactionId
        }
        const actionData = { url: sendUrl, method: 'POST', data: sendData }
        channelConfigMoudle.channelCommonAction(actionData).then(res => {
          if (res && res.success) {
            this.$message.success(successMsg)
            if (sendData._id) { // 编辑直接关闭抽屉
              (this as any).$updateCache('channelList', res.data, '_id', true)
            }
            this.drawer.isShow = false
            this.getTableList(sendData._id === '' ? 'add' : null)
          }
        })
      }
    })
  }

  private getTableList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.tablePages.current = 1
    }
    const sendData = { limit: this.tablePages.pageSize, page: this.tablePages.current }
    const actionData = { url: '/im-wxsdk/action/config/wxsdkChannel/list', method: 'POST', data: sendData }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res.data.list) {
        const list = res.data.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.tablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.tablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.tablePages.current = page
            this.getTableList()
            return false
          }
        }
        if (list.length > 0) {
          list.forEach((item: any) => {
            const processObj = deepClone(CommonModule.publicCache.processListObj)[item.processId]
            item.processName = processObj ? processObj.name : '--'
            const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.createUser]
            item.createName = agentObj ? agentObj.name : '--' // 创建人
          })
        }
        this.tableData = res.data.list
        this.tablePages.total = res.data.count || 0
      }
    })
  }

  private mounted () {
    let handlers: any = []
    this.limitArr = this.$store.state.common.session.user.functions // 权限处理
    if (checkPermission(null, { value: ['wechatApp_sdk_access_list_edit'] })) { // 编辑权限
      handlers.push({ name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) })
    }
    if (checkPermission(null, { value: ['wechatApp_sdk_access_list_delete'] })) { // 删除权限
      handlers = [...handlers,
        ...[
          { name: '删除', className: 'danger', handleFn: (scope: any) => this.delFun(scope.row) }
        ]
      ]
    }
    this.tableHeader.push({ label: '操作', width: 220, handlers })
    const channelCache = this.$getCache('/im-center/action/webchat/channelCache', ['wxsdkCssList'], true) // 获取样式缓存
    const processCache = this.$getCache('/im-center/action/config/processConfig/processCache', ['processList'], true)
    Promise.all([channelCache, processCache]).then((res: any) => {
      if (res) {
        this.getTableList()
      }
    })
    const actionData = { url: '/im-center/action/config/satisfaction/list', method: 'POST', data: {} }
    channelConfigMoudle.channelCommonAction(actionData).then(res => {
      if (res && res.success && res.data && res.data.list) {
        const currentObj = res.data.list.filter(item => {
          return item.isDefault
        })
        this.satisfactionId = currentObj[0]._id
      }
    })
  }
}
</script>
<style lang="stylus" scoped>
  .accessListDrawer
    >>> .drawer-contain
      height auto
      padding 6px 20px
  .accessList
    border 1px solid $border-main
    padding 16px
    border-radius 10px
    height 100%
    overflow auto
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
    box-sizing border-box
    margin 0 2px 2px 0
    height calc(100% - 40px)
    .top
      height 115px
      background-color #F4F9FD
      border-radius 4px
      width 100%
      padding 20px
      .icon
        width 40px
        height 40px
        line-height 40px
        text-align center
        margin 10px 11px 0px 0px
        background-color #53C931
        border-radius 50%
        .V7_iconfont
          color #fff
          font-size 24px
      .title
        color $fc-gray2
        margin-bottom 5px
      .add
        margin-top 15px
      .version
        background #FFFFFF
        border 1px solid $border-main
        border-radius 4px
        padding 0px 12px
        height 30px
        line-height 30px
        display inline-block
        margin-top 5px
        a
          margin-left 14px
      p
       color #686E84
    .instiutionTableBox
      height calc(100% - 115px)
</style>
